package com.minisoft.online;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LogTimeAnalyzer {
    public static void main(String[] args) {
        String logFilePath = "D:\\temp\\OnlineSalesBatchSvc.log_1";
        analyzeLogFile(logFilePath);
    }

    public static void analyzeLogFile(String filePath) {
        // 用于存储耗时统计的Map，key为时间区间上限，value为计数
        Map<Integer, Integer> timeDistribution = new TreeMap<>();
        int totalRequests = 0;
        int maxTime = 0;
        int minTime = Integer.MAX_VALUE;
        long totalTime = 0;

        // 正则表达式匹配耗时信息
        Pattern pattern = Pattern.compile("cost: (\\d+) ms");

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                Matcher matcher = pattern.matcher(line);
                if (matcher.find()) {
                    int costTime = Integer.parseInt(matcher.group(1));
                    totalRequests++;
                    totalTime += costTime;
                    
                    // 更新最大最小耗时
                    if (costTime > maxTime) maxTime = costTime;
                    if (costTime < minTime) minTime = costTime;
                    
                    // 计算所属的时间区间
                    int timeBucket = (costTime / 10) * 10;
                    timeDistribution.put(timeBucket, timeDistribution.getOrDefault(timeBucket, 0) + 1);
                }
            }
        } catch (IOException e) {
            System.err.println("Error reading log file: " + e.getMessage());
            return;
        }

        // 打印统计结果
        System.out.println("请求耗时统计结果:");
        System.out.println("总请求数量: " + totalRequests);
        if (totalRequests > 0) {
            System.out.println("平均耗时: " + (totalTime / totalRequests) + " ms");
            System.out.println("最小耗时: " + minTime + " ms");
            System.out.println("最大耗时: " + maxTime + " ms");
            System.out.println("\n耗时分布 (每10ms为一个区间):");
            
            // 确保所有区间都被显示，即使计数为0
            int maxBucket = (maxTime / 10) * 10;
            for (int i = 0; i <= maxBucket; i += 10) {
                int count = timeDistribution.getOrDefault(i, 0);
                if (count > 0) {
                    System.out.printf("%d-%dms: %d%n", i, i+10, count);
                }
            }
        }
    }
}